<route lang="json5">
{
  style: {
    navigationBarTitleText: '还书',
    navigationStyle: 'custom',
    disableScroll: true,
    // #ifdef MP-ALIPAY
    enablePullDownRefresh: false,
    'mp-alipay': {
      allowsBounceVertical: 'NO',
      transparentTitle: 'always',
      titlePenetrate: 'YES',
      defaultTitle: '',
    },
    // #endif
  },
}
</route>
<template>
  <CustomNavbar :type="SearchTypeEnum.ORDER" :direction="OrderDirection.OUTPUT" />
  <view class="uni-margin-wrap">
    <view class="type-box">
      <view class="text" v-for="(item, index) in typeList" :key="item" @tap="clickType(index)">
        <text>{{ item }}</text>
      </view>
    </view>
    <uni-transition
      ref="cursor"
      custom-class="custom-transition"
      :show="true"
      mode-class="slide-left"
    />
    <swiper class="swiper" :current="activeIndex" @change="changeSwiper">
      <swiper-item class="swiper-item" v-for="(pageDataItems, index) in dataList" :key="index">
        <scroll-view
          :scroll-top="scrollTop"
          :scroll-y="true"
          class="scroll-Y"
          refresher-enabled
          :refresher-triggered="isTriggered"
          @refresherrefresh="upper"
          @scrolltolower="lower"
        >
          <uni-card
            :title="'《' + recordItem.bookName + '》'"
            :sub-title="'作者: ' + recordItem.bookAuthor"
            :extra="recordItem.statusStr"
            :thumbnail="recordItem.bookAvatar"
            v-for="recordItem in pageDataItems"
            :key="recordItem.id"
          >
            <view class="options">
              <text>订单号: {{ recordItem.orderId }}</text>
              <text>借阅人: {{ recordItem.borrowUserName }}</text>
              <text>到期时间: {{ recordItem.deadline }}</text>
              <button
                v-if="recordItem.status === OrderStatus.BORROWING"
                class="mini-btn .button1"
                hover-class="button-active"
                size="mini"
                @tap="updateStatus(recordItem, OrderStatus.APPROVE)"
              >
                同意
              </button>
              <button
                v-if="recordItem.status === OrderStatus.BORROWING"
                class="mini-btn .button2"
                hover-class="button-active"
                size="mini"
                @tap="updateStatus(recordItem, OrderStatus.REJECTED)"
              >
                拒绝
              </button>
              <button
                v-if="recordItem.status === OrderStatus.RETURN"
                class="mini-btn .button1"
                hover-class="button-active"
                size="mini"
                @tap="updateStatus(recordItem, OrderStatus.DONE)"
              >
                确认归还
              </button>
            </view>
            <view class="remarks">
              <image
                v-if="recordItem.status != 0"
                style="width: 60rpx; height: 60rpx; border-radius: 50%"
                :src="recordItem.borrowUserAvatar"
                mode="scaleToFill"
              />
              <text v-if="recordItem.status != 0" class="uni-body">
                &nbsp;: {{ recordItem.remark }}
              </text>
            </view>
          </uni-card>
          <uni-load-more
            v-if="pageDataItems.length > 7"
            class="loading-text"
            :status="loadingStatus"
            :content-text="MORE_MSG_OBJ"
          />
          <div style="width: 100rpx; height: 300rpx"></div>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script lang="ts" setup>
import CustomNavbar from './components/CustomNavbar.vue'
import { MORE_MSG_OBJ } from '@/store/contants'
import { useUserStore } from '@/store/user'
import { myOrderListApi, updateStatusApi } from '@/service/order'
import { OrderStatus, OrderDirection } from '@/enums/OrderStatus'
import { Book } from '@/types/book'
import { Order } from '@/types/order'
import { PageParam } from '@/types/global'
import { SearchTypeEnum } from '@/enums/SearchTypeEnum'

const activeIndex = ref(0)
const cursor = ref()
const userInfo = useUserStore().userInfo

const loadingStatus = ref()

const typeList = ['全部', '借阅中', '已逾期', '已完成']

const scrollTop = ref(0)
const isTriggered = ref(false)
const allPageParams: Required<PageParam> = { page: 1, size: 10 }
const borrowPageParams: Required<PageParam> = { page: 1, size: 10 }
const expiredPageParams: Required<PageParam> = { page: 1, size: 10 }
const returnedPageParams: Required<PageParam> = { page: 1, size: 10 }

const dataList = ref<Order[][]>([[], [], [], []])

onLoad(async () => {
  await initData()
})

const initData = async () => {
  const allListRes = await initAllList()
  dataList.value[0] = allListRes.data.records
  const borrowListRes = await initBorrowList()
  dataList.value[1] = borrowListRes.data.records
  const expiredListtRes = await initExpiredList()
  dataList.value[2] = expiredListtRes.data.records
  const ReturnedListRes = await initReturnedList()
  dataList.value[3] = ReturnedListRes.data.records
  console.log(dataList.value)
}

const initAllList = async () => {
  return await myOrderListApi({
    direction: OrderDirection.OUTPUT,
    status:
      OrderStatus.BORROWING +
      ',' +
      OrderStatus.APPROVE +
      ',' +
      OrderStatus.EXCEEDING +
      ',' +
      OrderStatus.RETURN +
      ',' +
      OrderStatus.DONE,
    page: allPageParams.page,
    size: allPageParams.size,
  })
}
const initBorrowList = async () => {
  return await myOrderListApi({
    direction: OrderDirection.OUTPUT,
    status: OrderStatus.APPROVE + ',',
    page: borrowPageParams.page,
    size: borrowPageParams.size,
  })
}
const initExpiredList = async () => {
  return await myOrderListApi({
    direction: OrderDirection.OUTPUT,
    status: OrderStatus.EXCEEDING + ',',
    page: expiredPageParams.page,
    size: expiredPageParams.size,
  })
}

const initReturnedList = async () => {
  return await myOrderListApi({
    direction: OrderDirection.OUTPUT,
    status: OrderStatus.DONE + ',',
    page: returnedPageParams.page,
    size: returnedPageParams.size,
  })
}

const updateStatus = async (order: Order, status: number) => {
  uni.showLoading({ title: '请稍后...' })
  const updateStatusRes = await updateStatusApi({ id: order.id, status })
  console.log('updateStatus res', updateStatusRes)
  order.status = updateStatusRes.data.status
  order.statusStr = updateStatusRes.data.statusStr
  uni.hideLoading()
  uni.showToast({
    title: '已提交',
    mask: true,
  })
}

const clickType = (index: number) => {
  activeIndex.value = index
  cursor.value.step(
    {
      translateX: activeIndex.value * 120 + '%',
    },
    {
      delay: 0,
      duration: 200,
      timingFunction: 'linear',
      needLayout: false,
      transformOrigin: '',
    },
  )
  cursor.value.run()
}

const changeSwiper = (ev) => {
  activeIndex.value = ev.detail.current
  cursor.value.step(
    {
      translateX: activeIndex.value * 120 + '%',
    },
    {
      delay: 0,
      duration: 200,
      timingFunction: 'linear',
      needLayout: false,
      transformOrigin: '',
    },
  )
  cursor.value.run()
}

// 触发下拉刷新
const upper = async () => {
  console.log('下拉刷新')
  isTriggered.value = true
  // 加载数据 api 要加 await
  // ...
  // await Promise.all([guessRef.value?.resetData()])
  if (activeIndex.value === 0) {
    allPageParams.page = 1
    const allListRes = await initAllList()
    dataList.value[0] = allListRes.data.records
  } else if (activeIndex.value === 1) {
    borrowPageParams.page = 1
    const borrowListRes = await initBorrowList()
    dataList.value[1] = borrowListRes.data.records
  } else if (activeIndex.value === 2) {
    expiredPageParams.page = 1
    const expiredListtRes = await initExpiredList()
    dataList.value[2] = expiredListtRes.data.records
  } else if (activeIndex.value === 3) {
    returnedPageParams.page = 1
    const ReturnedListRes = await initReturnedList()
    dataList.value[3] = ReturnedListRes.data.records
  }
  loadingStatus.value = 'more'
  setInterval(() => {
    isTriggered.value = false
  }, 1000)
}
const lower = async () => {
  console.log('lower')
  if (dataList.value[activeIndex.value].length < 10) {
    return
  }
  loadingStatus.value = 'loading'
  if (activeIndex.value === 0) {
    allPageParams.page++
    const allListRes = await initAllList()
    if (allListRes.data.records.length !== 0) {
      dataList.value[0].push(...allListRes.data.records)
      loadingStatus.value = 'more'
      return
    }
  } else if (activeIndex.value === 1) {
    borrowPageParams.page++
    const borrowListRes = await initBorrowList()
    if (borrowListRes.data.records.length !== 0) {
      dataList.value[1].push(...borrowListRes.data.records)
      loadingStatus.value = 'more'
      return
    }
  } else if (activeIndex.value === 2) {
    expiredPageParams.page++
    const expiredListtRes = await initExpiredList()
    if (expiredListtRes.data.records.length !== 0) {
      dataList.value[2].push(...expiredListtRes.data.records)
      loadingStatus.value = 'more'
      return
    }
  } else if (activeIndex.value === 3) {
    returnedPageParams.page++
    const ReturnedListRes = await initReturnedList()
    if (ReturnedListRes.data.records.length !== 0) {
      dataList.value[3].push(...ReturnedListRes.data.records)
      loadingStatus.value = 'more'
      return
    }
  }
  allPageParams.page--
  uni.showToast({
    title: '没有了',
    icon: 'none',
  })
  loadingStatus.value = 'noMore'
}
</script>

<style lang="scss">
.uni-margin-wrap {
  width: 690rpx;
  width: 100%;
}

.type-box {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-top: 10rpx;
  font-size: 33rpx;
}

.type {
  border-bottom: 1px solid red;
}

.text {
  width: 25%;
  text-align: center;
}
/* 如果使用 scss 需要使用 /deep/  */
.custom-transition {
  position: absolute;
  width: 22%;
  height: 7rpx;
  margin-top: 7rpx;
  background-color: $main-color;
}

.swiper {
  height: calc(100vh - var(--window-top));
  margin-top: 10rpx;

  .swiper-item {
    .uni-body {
      font-size: 32rpx;
      color: #a5a5a5;
    }
  }
}

.options {
  width: 100%;
  margin-bottom: 10rpx;

  text {
    display: block;
    font-size: 28rpx;
    color: $main-color-hight;
  }

  .button1 {
    float: right;
    margin-left: 20rpx;
    font-size: 30rpx;
    color: #fff;
    background-color: $main-color-hight;
  }
  .button2 {
    float: right;
    font-size: 30rpx;
    color: #fff;
    background-color: $uni-color-error;
  }

  .button-active {
    background-color: $main-color; /* 点击时的背景颜色 */
  }
}
.remarks {
  width: 70%;
  margin-left: 5%;
}

.scroll-Y {
  width: 100%;
  height: calc(100vh - var(--window-top));
}
</style>
